package online.yysh.charging.base;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import online.yysh.charging.bean.Login;
import online.yysh.charging.livedata.UserManager;
import online.yysh.charging.utils.Constant;

public abstract class BaseActivity extends AppCompatActivity {

    protected String TAG = getClass().getSimpleName();

    protected String openid = "";
//    protected String oid = "";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(savedInstanceState);
    }

    protected void init(Bundle savedInstanceState) {
        SharedPreferences sp = getSharedPreferences(Constant.SP_NAME, Context.MODE_PRIVATE);
        openid = sp.getString(Constant.SP_KEY_OPENID,"");
//        oid = sp.getString(Constant.SP_KEY_OID,"");
        UserManager.getInstance().getLiveData().observe(this, new Observer<Login>() {
            @Override
            public void onChanged(Login login) {
                openid = login.getOpenid();
            }
        });
        initLayout();
        initView(savedInstanceState);
        initData();
    }

    protected void initLayout() {
        if (getLayoutId() > 0) {
            setContentView(getLayoutId());
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    protected void showToast(final String msg) {
        if ("main".equals(Thread.currentThread().getName())){
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }else{
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 当前日志等级
     * debug:0
     * error:1
     * non:2
     */
    protected int currentLogLevel;

    protected void logD(String msg) {
        if (currentLogLevel == 0) {
            Log.d(TAG, msg);
        }
    }

    protected void logE(String msg) {
        if (currentLogLevel < 2) {
            Log.e(TAG, msg);
        }
    }

    protected void startActivity(Class clazz) {
        startActivity(new Intent(this, clazz));
    }
}
